<?php
include_once('class-profiler.php');

class COptions{

	private static $instance = null;

	function __construct(){
		add_action('admin_init', array($this,'init'));
		add_action('admin_menu', array($this,'add_page'));
		if ( isset( $_GET['page'] ) && $_GET['page'] == 'vp_options' ) {
			add_action('admin_head', array($this,'do_ajax'));
			wp_enqueue_style('datatables-demo', TEMPLATEURL . 'css/datatables-demo.css');
			wp_enqueue_script('jquery-1.5', TEMPLATEURL . 'js/jquery-1.5.js');
			wp_enqueue_script('datatables', TEMPLATEURL . 'js/jquery.dataTables.min.js');
			wp_enqueue_script('json');
			wp_enqueue_script('swfobject');
		}
		add_action('wp_ajax_render_chart', array($this,'render_chart'));
	}
	
	public function get_instance(){
		if(is_null(self::$instance)) {
			self::$instance = new COptions();  
		}
 		return self::$instance;
	}
	
	// Init Carbon Paper template options
	function init(){
	        register_setting( 'vp_options', 'voteprofiler', array($this,'validate' ));
	}
	
	// Add Carbon Paper options item in admin menu
	function add_page() {
	        add_options_page('Vote Profiler Options', 'Vote Profiler', 'manage_options', 'vp_options', array($this,'do_page'));
	}

	
	// Draw the menu page itself
	function do_page() {
			$oProfiler = CProfiler::get_instance();
		?>
		<div class="wrap">
			<div id="icon-options-general" class="icon32"><br></div>
			<h2>Vote Profiler Options</h2>
			<h3>Paramètres</h3>
			<form method="post" action="options.php">
				<?php settings_fields('vp_options'); ?>
				<?php $parameters = $oProfiler->get_parameters(); ?>
				<table class="form-table">
					<tr valign="top"><th scope="row">Included Type(s)</th>
						<td><input type="text" name="voteprofiler[included_types]" value="<?php echo $parameters['included_types']; ?>" /></td>
					</tr>
					<tr valign="top"><th scope="row">Duration (hours)</th>
						<td><input type="text" name="voteprofiler[duration]" value="<?php echo $parameters['duration']; ?>" /></td>
					</tr>
					<tr valign="top"><th scope="row">Peak location (hours)</th>
						<td><input type="text" name="voteprofiler[location]" value="<?php echo $parameters['location']; ?>" /></td>
					</tr>
					<tr valign="top"><th scope="row">Jobs execution interval (hours)</th>
						<td><input type="text" name="voteprofiler[interval]" value="<?php echo $parameters['interval']; ?>" /></td>
					</tr>
					<tr valign="top"><th scope="row">Day Job Rule</th>
						<td><input type="checkbox" name="voteprofiler[dayjob_rule]" value="1" <?php checked('1',$parameters['dayjob_rule']); ?>" /></td>
					</tr>
					<tr valign="top"><th scope="row">Weekday Job Rule</th>
						<td><input type="checkbox" name="voteprofiler[weekdayjob_rule]" value="1" <?php checked('1',$parameters['weekdayjob_rule']); ?>" /></td>
					</tr>
<!--					<tr valign="top"><th scope="row">Error Margin(%)</th>
							<td><input type="text" name="voteprofiler[r]" value="<?php echo $parameters['r']; ?>" /></td>
					</tr>-->
				</table>
				<p class="submit">
				<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
				</p>

				<script type="text/javascript" charset="utf-8"> 
					$(document).ready(function() {
						$('#vote-list').dataTable( {
							//"sScrollY": "200px",
							"bPaginate": true,
							"sPaginationType": "full_numbers",
							"bLengthChange": false,
							"bFilter": true,
							"bSort": false,
							"bInfo": false,
							"bAutoWidth": false } );
					} );
				</script> 
					
		<h3>Gains en cours :</h3>
		<table id="vote-list" class="wp-list-table widefat" cellspacing="0">
		<thead>
		<tr>
			<th></th>
			<th>Post</th>
			<th>Date</th>
			<th>Current Session</th>
			<th>ID</th>
			<th>Goal</th>
			<th>Score</th>
			<th>Cumuled Gain</th>
			<th>User Gain</th>
		</tr>
		</thead>
		<tbody>
		<?php
		$posts = $oProfiler->get_posts_by_duration();
		if ($posts){
			foreach ($posts as $oPost) {
				$votes = $oPost->get_votes(); 
				if ($votes){
					foreach ($votes as $oVote) {
						echo " 
						<tr id=\"{$oPost->get_ID()}\" class=\"alternate author-self status-publish format-default iedit\">
						<td><a href=\"\" class=\"chart\" rel=\"{$oVote->get_post_ID()}__{$oVote->get_ID()}\">chart</a></td>
						<td>{$oPost->get_ID()} - {$oPost->get_title()}</td>
						<td>{$oPost->get_date()}</td>
						<td>{$oVote->get_session()} / {$oVote->get_scope()}</td>
						<td>{$oVote->get_title()}</td>
						<td>{$oVote->get_goal()}</td>
						<td>{$oVote->get_score()}</td>
						<td>{$oVote->get_cumuled_gain()}</td>
						<td>{$oVote->get_user_gain()}</td>
						</tr>";
					}
				}
			}			
		}
		?>
		</tbody>
		<tfoot>
		<tr>
			<th></th>
			<th>Post</th>
			<th>Date</th>
			<th>Current Session</th>
			<th>ID</th>
			<th>Goal</th>
			<th>Score</th>
			<th>Cumuled Gain</th>
			<th>User Gain</th>
		</tr>
		</thead>
		</table>
		<div id="chart"></div>
	</form>
	</div>
	<?php
	}
	// Sanitize and validate input. Accepts an array, return a sanitized array.
	public function validate($input) {
		// Say our second option must be safe text with no HTML tags
		$input['included_types']	=  wp_filter_nohtml_kses($input['included_types']);
		$input['duration'] 		 	=  wp_filter_nohtml_kses($input['duration']);
		$input['location'] 		 	=  wp_filter_nohtml_kses($input['location']);
		$input['interval'] 			=  wp_filter_nohtml_kses($input['interval']);
		$input['dayjob_rule'] 		=  wp_filter_nohtml_kses($input['dayjob_rule']);
		$input['weekdayjob_rule'] 	=  wp_filter_nohtml_kses($input['weekdayjob_rule']);
		$input['r'] 				=  wp_filter_nohtml_kses($input['r']);
		return $input;
	}

	function do_ajax() {
	?>
    <script type="text/javascript">
	jQuery(document).ready(function($) {
		jQuery.ajaxSetup({cache:false});
		jQuery('a.chart').click(function(){
		  var data = {
			action: 'render_chart',
			ids: jQuery(this).attr("rel") 
		  };
		  jQuery('#chart').html("Chargement...");
		  jQuery('#chart').load(ajaxurl,data,function(response) {
			//alert('Got this from the server: ' + response);
		  });
		  return false;
	  });
	});
	</script>
	<?php
	}

	function render_chart() {
		//$_POST['ids'] = '2415___reaction_buttons_WOW';
		$ids = explode('__',$_POST['ids']);
		$oProfiler = CProfiler::get_instance();
		$oPost = $oProfiler->get_post_by_ID($ids[0]);
		$oVote = $oPost->get_vote_by_ID($ids[1]);
		//print_r($oVote);exit();
		$oVote->render();
		die();
	}
}
?>